package com.yungam.imcs.controller.energy;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Maps;
import com.yungam.common.bean.energy.Energy;
import com.yungam.common.bean.equip.Equipment;
import com.yungam.common.response.RetDTO;
import com.yungam.common.service.EnergyService;
import com.yungam.common.service.EquipmentService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

@Api(tags = "历史能量数据接口")
@RestController
@RequestMapping("/energy")
public class EnergyHistoryController {

    @Resource
    private EnergyService energyService;
    @Resource
    private EquipmentService equipmentService;

    /**
     * 历史能量数据分页查询
     * @param start
     * @param end
     * @param pageNum
     * @param pageSize
     * @return
     */
    @ApiOperation("历史能量数据分页查询")
    @GetMapping("/data")
    public RetDTO<?> getHistoryData(@ApiParam("开始时间")    @RequestParam(required = false) String start,
                                    @ApiParam("结束时间")    @RequestParam(required = false) String end,
                                    @ApiParam("页号")    @RequestParam(required = true) int pageNum,
                                    @ApiParam("每页数量") @RequestParam(required = true) int pageSize) {
        List<Equipment> equipmentList = equipmentService.list(new QueryWrapper<Equipment>()
                .select(Equipment.class, col -> !col.getProperty().equals("equImg")));
        Map<Integer, Equipment> map = Maps.newHashMap();
        for (Equipment equipment : equipmentList) map.put(equipment.getEquId(), equipment);

        QueryWrapper<Energy> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("day");
        if (StringUtils.isNotBlank(start)) queryWrapper.ge("day", start);
        if (StringUtils.isNotBlank(end)) queryWrapper.le("day", end);

        IPage<Energy> page = new Page<>(pageNum, pageSize);
        page = energyService.page(page, queryWrapper);
        List<Energy> records = page.getRecords();
        for (Energy record : records) {
            if (map.containsKey(record.getEquId())) record.setEquipment(map.get(record.getEquId()));
        }
        page.setRecords(records);
        return RetDTO.data(page);
    }
}
